/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.dao;

import org.ipti.br.tag.entity.Discipline;
import org.ipti.br.tag.entity.Discipline_;
import org.ipti.br.tag.entity.UnitySchedule;
import org.ipti.br.tag.entity.UnitySchedule_;
import org.ipti.br.tag.entity.Unity_;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.ipti.br.tag.util.EncryptionUtil;

/**
 *
 * @author israel
 */
@Stateless
public class DisciplineFacade extends AbstractFacade<Discipline> {

    @PersistenceContext(unitName = "TAG2PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public DisciplineFacade() {
        super(Discipline.class);
    }

    @Override
    public void create(Discipline discipline) {
        getEntityManager().persist(discipline);
    }

    @Override
    public void edit(Discipline discipline) {
        discipline.setSerialNumber(null);

        getEntityManager().merge(discipline);
    }

    public void editForSynchronization(Discipline discipline) {
        getEntityManager().merge(discipline);
    }

    public List<Discipline> findAllOrder() {
        return findAllOrderBy(Discipline_.name);
    }
    
    public List<Discipline> searchDisciplinesPerUnity (Long unityID) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<Discipline> cq = cb.createQuery(Discipline.class);
        Root<UnitySchedule> root = cq.from(UnitySchedule.class);
        cq.select(root.join(UnitySchedule_.discipline));
        cq.distinct(true);
        
        cq.where(cb.and(
                cb.equal(root.join(UnitySchedule_.unity).get(Unity_.id), unityID)));
        cq.orderBy(cb.asc(root.join(UnitySchedule_.discipline).get(Discipline_.name)));
        
        Query q = getEntityManager().createQuery(cq);
        return q.getResultList();
    }
}
